package com.mofang.ticketing.base.serve.area.service.impl;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.mofang.ticketing.base.mapping.entity.SysCityDO;
import com.mofang.ticketing.base.mapping.entity.SysCountyDO;
import com.mofang.ticketing.base.mapping.entity.SysProvinceDO;
import com.mofang.ticketing.base.mapping.mapper.SysCityDOMapper;
import com.mofang.ticketing.base.mapping.mapper.SysCountyDOMapper;
import com.mofang.ticketing.base.mapping.mapper.SysProvinceDOMapper;
import com.mofang.ticketing.base.serve.area.pojo.response.AreaRespDTO;
import com.mofang.ticketing.base.serve.area.service.IAreaService;
import com.mofang.ticketing.common.redis.constant.RedisConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @BelongsProject: pms-group-digitization
 * @BelongsPackage: com.mofang.base.font.service.impl
 * @Author: jc
 * @CreateTime: 2022-05-20  11:04
 * @Version: 1.0
 */
@Slf4j
@Service
public class AreaServiceImpl implements IAreaService {

    @Resource
    private SysProvinceDOMapper sysProvinceDOMapper;
    @Resource
    private SysCityDOMapper sysCityDOMapper;
    @Resource
    private SysCountyDOMapper sysCountyDOMapper;

    @Override
    @Cacheable(value = RedisConstant.AREA_KEY, unless = "#result==null")
    public List<AreaRespDTO> areaList() {
        List<SysProvinceDO> provinces = sysProvinceDOMapper.selectList(Wrappers.emptyWrapper());
        List<SysCityDO> cities = sysCityDOMapper.selectList(Wrappers.emptyWrapper());
        List<SysCountyDO> counties = sysCountyDOMapper.selectList(Wrappers.emptyWrapper());

        if (provinces != null && provinces.size() > 0
                && cities != null && cities.size() > 0
                && counties != null && counties.size() > 0) {
            return provinces.stream().map(p -> {
                // 市
                List<AreaRespDTO> citys = cities.stream().filter(c -> c.getProvinceCode().equals(p.getCode()))
                        .map(c -> {
                            // 区
                            List<AreaRespDTO> countys = counties.stream().filter(t -> t.getCityCode().equals(c.getCode()))
                                    .map(t -> new AreaRespDTO(t.getCode(), t.getName(), t.getPinyin(), null)).collect(Collectors.toList());
                            return new AreaRespDTO(c.getCode(), c.getName(), c.getPinyin(), countys);
                        }).collect(Collectors.toList());

                return new AreaRespDTO(p.getCode(), p.getName(), p.getPinyin(), citys);
            }).collect(Collectors.toList());
        }
        return null;
    }

}
